class CatalogoController < ApplicationController
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @catalogos = Catalogo.paginate :page => params[:page], :per_page => DEFAULT_PER_PAGE, :order => 'nombre'

  end

  def show
    @catalogo = Catalogo.find(params[:id])
    if @catalogo.parent_id
      @catalogo_parent = Catalogo.find(@catalogo.parent_id)
    else
      @catalogo_parent = nil
    end
  end

  def new
    @catalogo = Catalogo.new
  end

  def create
    @catalogo = Catalogo.new(params[:catalogo])
    
    if @catalogo.parent_id == 0
       @catalogo.parent_id = nil
    end
    
    if @catalogo.save
      flash[:notice] = 'El Catalogo se creo correctamente.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @catalogo = Catalogo.find(params[:id])
  end

  def update
    @catalogo = Catalogo.find(params[:id])
    if @catalogo.update_attributes(params[:catalogo])
      flash[:notice] = 'El Catalogo se actualizo correctamente.'
      redirect_to :action => 'show', :id => @catalogo
    else
      render :action => 'edit'
    end
  end
  
  def add_entrada
    @catalogo = Catalogo.find(params[:id])
    @catalogo.entradas_catalogo.build(params[:entrada])
    
    if @catalogo.save
      flash[:notice] = 'Se agrego correctamente el Valor al Catalogo.'
    else
      flash.now[:error] = "No se agrego correctamente el Valor al Catalogo."
    end    
    redirect_to :action => "show", :id => @catalogo
  end

  def destroy
    Catalogo.find(params[:id]).destroy
    redirect_to :action => 'list'
  end
end
